package com.wandian.cqcsk.mvvm.mine.sethomebtn;

import android.os.Bundle;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.TabKeyUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.widget.DragRecycleView;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.mine.HomeBtnDragRecycleAdapter;
import com.wandian.cqcsk.adapter.mine.MineHomeBtnRecycleAdapter;
import com.wandian.cqcsk.databinding.ActivitySetHomeBtnBinding;
import com.wandian.cqcsk.mvvm.main.MainActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import static com.mylib.libcore.config.AppSPKeyConfig.APP_FUNCTION_TABS;
import static com.mylib.libcore.config.AppSPKeyConfig.FIRST_OPEN_PAGE_TEXT;
import static com.mylib.libcore.config.AppSPKeyConfig.FIRST_PAGE_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.HOME_TAB_JSON;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description SetHomeBtnActivity
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_SET_HOME_BTN)
public class SetHomeBtnActivity extends BaseMVVMActivity<SetHomeBtnViewModel> {
    private ActivitySetHomeBtnBinding dataBinding;
    private HomeBtnDragRecycleAdapter adapter;
    private DragRecycleView dragRecycleView;
    private MineHomeBtnRecycleAdapter mineHomeBtnRecycleAdapter;
    private boolean isEdit = false;
    private ArrayList<String> lisTitleSelect = new ArrayList<>();
    private String fixedString = "我的";//固定不可去掉
    private final int maxnum = 5;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_set_home_btn);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initViewData();
        initClink();
        initTopRecycle();
        initSortRecycle();
    }

    private void initViewData(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("主页功能");
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.VISIBLE);
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setText("编辑");
    }

    private void initClink(){
        dataBinding.bindTransparentToolBar.toolBarIvBack.setOnClickListener(v -> finish());
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setOnClickListener(v -> {
            if(dataBinding.bindTransparentToolBar.toolBarTitleRight.getText().toString().equals("保存并更新")){
                String defaultText =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue(FIRST_PAGE_NAME);
                boolean haveDefaultText = false;
                if(!UIUtils.isEmpty(defaultText)){
                    for(String text:lisTitleSelect){
                        if(text.equals(defaultText))haveDefaultText =true;
                    }
                }
                if(!haveDefaultText) AppContext.getInstance().getAppPreferencesHelper().setKeyValue(FIRST_PAGE_NAME,FIRST_OPEN_PAGE_TEXT);
                AppContext.getInstance().getAppPreferenceForever().setSelectTabs( JsonUtil.toJson(lisTitleSelect));
                ActivityUtil.getInstance().finishActivity(MainActivity.class);//指定关闭首页
                ARouter.getInstance().build(RouterConfig.ROUTER_MAIN).navigation();

            }else {
                isEdit = !isEdit;
                if(isEdit){
                    dataBinding.bindTransparentToolBar.toolBarTitleRight.setText("保存并更新");
                }else {
                    dataBinding.bindTransparentToolBar.toolBarTitleRight.setText("编辑");
                }
                mineHomeBtnRecycleAdapter.notifySelectState(isEdit,lisTitleSelect);
            }

        });
    }

    private void initTopRecycle(){
        lisTitleSelect.clear();
        String tableJson = AppContext.getInstance().getAppPreferenceForever().getSelectTabs();
        String tabs = AppContext.getInstance().getAppPreferenceForever().getMainTabs()+"";
        if(UIUtils.isEmpty(tableJson)){//默认底部选项
            if(tabs.contains("天气"))lisTitleSelect.add("天气");
            if(tabs.contains("资讯"))lisTitleSelect.add("资讯");
            lisTitleSelect.add("生活");
            lisTitleSelect.add("智库");
            AppContext.getInstance().getAppPreferenceForever().setSelectTabs( JsonUtil.toJson(lisTitleSelect));
        }else {
            try {
                JSONArray jsonArray = new JSONArray(tableJson);
                if(!UIUtils.isEmpty(jsonArray) && jsonArray.length()>0){
                    for(int i=0;i<jsonArray.length();i++){
                        String key = jsonArray.getString(i)+"";
                        if(TabKeyUtils.checkTabCanUse(key)){//没限制直接添加
                            lisTitleSelect.add(key);
                        } else{
                            if(tabs.contains(key))lisTitleSelect.add(key);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        adapter = new HomeBtnDragRecycleAdapter(R.layout.common_item_recycle_text_btn,lisTitleSelect);
        dragRecycleView = new DragRecycleView();
        dragRecycleView.initCustomDragRecycler(dataBinding.recycler,adapter,4,fixedString);
        dragRecycleView.notifyDragRecycleViewData(lisTitleSelect);
        adapter.setNewData(lisTitleSelect);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ToastUtil.show("默认打开-"+baseQuickAdapter.getData().get(i).toString());
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(FIRST_PAGE_NAME,baseQuickAdapter.getData().get(i).toString());
                adapter.setItemSelect(baseQuickAdapter.getData().get(i).toString());
            }
        });
    }

    private void initSortRecycle(){
        mineHomeBtnRecycleAdapter = new MineHomeBtnRecycleAdapter(R.layout.item_recycle_text_btn_edit,lisTitleSelect);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this,4);
        dataBinding.recyclerSort.setLayoutManager(layoutManager);
        dataBinding.recyclerSort.setAdapter(mineHomeBtnRecycleAdapter);
        String tabs = AppContext.getInstance().getAppPreferenceForever().getMainTabs()+"";
        List<String> lisTitle = new ArrayList<>();
        if(tabs.contains("天气"))lisTitle.add("天气");
        if(tabs.contains("资讯"))lisTitle.add("资讯");
        if(tabs.contains("游戏"))lisTitle.add("游戏");
        if(tabs.contains("玩赚"))lisTitle.add("玩赚");
        if(tabs.contains("小说"))lisTitle.add("小说");
        if(tabs.contains("音乐"))lisTitle.add("音乐");
        if(tabs.contains("视频"))lisTitle.add("视频");
        if(tabs.contains("微文"))lisTitle.add("微文");
        lisTitle.add("生活");
        lisTitle.add("智库");
        mineHomeBtnRecycleAdapter.setNewData(lisTitle);
        mineHomeBtnRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                if(isEdit){
                    lisTitleSelect = dragRecycleView.getLisTitle();
                    String itemString = baseQuickAdapter.getData().get(position).toString();
                    if(!itemString.equals(fixedString)){
                        boolean isAdd = true;
                        int index = 0;
                        for(int i=0;i<lisTitleSelect.size();i++){
                            if(itemString.equals(lisTitleSelect.get(i))){
                                isAdd = false;
                                index = i;
                                break;
                            }
                        }
                        if(isAdd){
                            if(lisTitleSelect.size()>=maxnum){
                                ToastUtil.show("亲，主页展示功能不能在加了~");
                            }else {
                                lisTitleSelect.add(itemString);
                                notifyUIAdapter();
                            }
                        }else {
                            lisTitleSelect.remove(index);
                            notifyUIAdapter();
                        }

                    }else {
                        ToastUtil.show("该项不可编辑");
                    }
                }
            }
        });
    }

    private void notifyUIAdapter(){
        dragRecycleView.notifyDragRecycleViewData(lisTitleSelect);
        adapter.setNewData(lisTitleSelect);
        adapter.notifyDataSetChanged();
        mineHomeBtnRecycleAdapter.notifySelectState(isEdit,lisTitleSelect);
    }
}
